﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using Newtonsoft.Json.Linq;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;
using System.Configuration;
using System.Threading;

namespace ZBZH_Manage_Order.Controllers.MerchantsSettings
{
    public class Order_DishesTypeController : Controller
    {
        //
        // GET: /Order_DishesType/

        ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取系统的增删查改的权限
        /// </summary>
        /// <returns></returns>
        public ActionResult getPower()
        {
            try
            {
                string[] PowerS = null;
                //string RetPower = "";
                Models.ControlPower RetPower = new Models.ControlPower();
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
                if (user != null)
                {
                    PowerS = user.RolePower.Split(',');//权限码
                    //拼接增删查改的权限
                    foreach (string pow in PowerS)
                    {
                        if (pow == "009005002")
                        {
                            RetPower.Add = 1;
                        }
                        else if (pow == "009005003")
                        {
                            RetPower.Dell = 1;
                        }
                        else if (pow == "009005004")
                        { RetPower.Edit = 1; }
                    }
                }
                else
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                return Json(RetPower);
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取当前操作员拥有商户的权限
        /// </summary>
        /// <returns></returns>
        public ActionResult getMer(JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.Order_Mer_T> page = new Page<Model.Order_Mer_T>();
                List<Model.Order_Mer_T> list = new List<Model.Order_Mer_T>();//定义商品分类设置
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                string result = service.GetMer(user.OperID, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            Model.Order_Mer_T m = new Model.Order_Mer_T();
                            m.MerID = item["MerID"].ToString();
                            m.MerName = item["MerName"].ToString();
                            m.MerAdr = item["MerAdr"].ToString();
                            m.MerCall = item["MerCall"].ToString();
                            m.MerTxt = item["MerTxt"].ToString();
                            list.Add(m);
                        }
                    }
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)//返回当前页的数据
                    };
                    return Json(data);
                }
                return Json(searcho["Msg"].ToString());
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="jqgridparam">datagrid页面参数</param>
        /// <returns></returns>
        public ActionResult getgrid(string MerID, JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.View_Order_DishesType> page = new Page<Model.View_Order_DishesType>();//分页类定义
                List<Model.View_Order_DishesType> list = new List<Model.View_Order_DishesType>();//定义商品分类设置
                string result = service.GetOrder_DishesType(MerID, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            Model.View_Order_DishesType m = new Model.View_Order_DishesType();
                            m.DishesTypeID = item["DishesTypeID"].ToString();
                            m.DishesTypeName = item["DishesTypeName"].ToString();
                            m.MerID = item["MerID"].ToString();
                            m.MerName = item["MerName"].ToString();
                            m.IntBZ = item["IntBZ"].ToString();
                            list.Add(m);
                        }
                    }
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)
                    };
                    return Json(data);
                }
                else if (bs == "0")
                {
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list
                    };
                    return Json(data);
                }
                else
                {
                    return Json(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 增、删、改一级商品分类
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="Order_DishesType"></param>
        /// <returns></returns>
        public ActionResult UpdateOrder_DishesType(int Tag, Model.Order_DishesType_T Order_DishesType)
        {
            try
            {
                string result = "";
                string dtjson = Order_DishesType.ToJson();
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                result = service.SetOrder_DishesType(user.OperID, dtjson, Tag, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    return Content(bs);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Content("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 增、删、改二级商品分类
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="PantID"></param>
        /// <param name="Order_DishesType"></param>
        /// <returns></returns>
        public ActionResult UpdateOrder_DishesType2(int Tag, string PantID, Model.Order_DishesType_T Order_DishesType)
        {
            try
            {
                string result = "";
                string dtjson = Order_DishesType.ToJson();
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }
                result = service.SetOrder_DishesType2(user.OperID, dtjson, Tag, PantID, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    #region 删除本地图片和文件夹
                    if (Tag == 3 && Order_DishesType.DishesTypeID != null)
                    {
                        //删除本地保存的图片文件夹                                 
                        string DishesTypesPic = ConfigurationManager.AppSettings["Order_DishesTypes_Photos"];
                        string DishesTypesPics = ConfigurationManager.AppSettings["WeChat_DishesTypes_Photos"];
                        string[] stringArray = new string[] { DishesTypesPic, DishesTypesPics };
                        foreach (var item in stringArray)
                        {
                            DirectoryInfo file = new DirectoryInfo((item + "/" + Order_DishesType.DishesTypeID).Replace('\\', '/'));
                            if (file.Exists)
                            {
                                DirectoryInfo[] childs = file.GetDirectories();
                                foreach (DirectoryInfo child in childs)
                                {
                                    child.Delete(true);
                                }
                                file.Delete(true);
                            }
                        }
                    }
                    #endregion

                    return Content(bs);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Content("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取一级商品分类数据
        /// </summary>
        /// <param name="jqgridparam">datagrid页面参数</param>
        /// <returns></returns>
        public ActionResult getgrids(JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.Order_DishesType_T> page = new Page<Model.Order_DishesType_T>();//分页类定义
                List<Model.Order_DishesType_T> list = new List<Model.Order_DishesType_T>();//定义商品分类设置 
                string result = service.Get_Order_DishesType_PC("", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            Model.Order_DishesType_T m = new Model.Order_DishesType_T();
                            m.DishesTypeID = item["DishesTypeID"].ToString();
                            m.DishesTypeName = item["DishesTypeName"].ToString();
                            m.Postion = Int32.Parse(item["Postion"].ToString());
                            list.Add(m);
                        }
                    }
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)
                    };
                    return Json(data);
                }
                else if (bs == "0")
                {
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list
                    };
                    return Json(data);
                }
                else
                {
                    return Json(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取二级商品分类数据
        /// </summary>
        /// <param name="DishesTypeID"></param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult getgridss(string DishesTypeID, JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.Order_DishesType_T> page = new Page<Model.Order_DishesType_T>();//分页类定义
                List<Model.Order_DishesType_T> list = new List<Model.Order_DishesType_T>();//定义商品分类设置 
                string result = service.Get_Order_DishesType_PC_T(DishesTypeID, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            Model.Order_DishesType_T m = new Model.Order_DishesType_T
                            {
                                DishesTypeID = item["DishesTypeID"].ToString(),
                                DishesTypeName = item["DishesTypeName"].ToString(),
                                PantID = item["PantID"].ToString(),
                                Postion = Int32.Parse(item["Postion"].ToString())
                            };
                            list.Add(m);
                        }
                    }
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)
                    };

                    List<Order_DishesType_T> list2 = new List<Order_DishesType_T>();
                    list2 = ParseClass<Order_DishesType_T>.JsonList(jieguo);
                    Session[SessionStorage.DishesTypeList] = list2;

                    return Json(data);
                }
                else if (bs == "0")
                {
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list
                    };
                    return Json(data);
                }
                else
                {
                    return Json(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex.Message + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取菜品照片
        /// </summary>
        /// <param name="DishesTypeID">菜品ID</param>
        /// <returns></returns>
        public ActionResult getDishesTypePhoto(string DishesTypeID)
        {
            try
            {
                string pic = "";
                List<Order_DishesType_T> list = (List<Order_DishesType_T>)Session[SessionStorage.DishesTypeList];
                foreach (Order_DishesType_T item in list)
                {
                    if (DishesTypeID == item.DishesTypeID)
                    {
                        pic = item.Icon;
                    }
                }
                return Content(pic);
            }
            catch (Exception) { return null; }
        }

        #region 原上传照片本地保存
        /// <summary>
        /// 原上传照片本地保存
        /// </summary>
        /// <param name="fileToUpload"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ToLead(HttpPostedFileBase[] fileToUpload, string id)
        {
            try
            {
                string FileUrl = string.Empty;
                //string daPic = Server.MapPath("~/DishesTypes");
                string DishesTypesPic = ConfigurationManager.AppSettings["Order_DishesTypes_Photos"] + "\\" + id;
                string DishesTypesPics = ConfigurationManager.AppSettings["WeChat_DishesTypes_Photos"] + "\\" + id;
                string[] stringArray = new string[] { DishesTypesPic, DishesTypesPics };

                foreach (var item in stringArray)
                {
                    if (!Directory.Exists(item))//判断目录是否存在
                    {
                        Directory.CreateDirectory(item);
                    }
                    foreach (HttpPostedFileBase file in fileToUpload)
                    {
                        string path = Path.Combine(item, Path.GetFileName(file.FileName));
                        file.SaveAs(path);
                        FileUrl = path;
                        FileStream Pic = new FileStream(path, FileMode.Open);
                        byte[] PicByte = new byte[Pic.Length];
                        Pic.Read(PicByte, 0, (int)Pic.Length);
                        Pic.Close();
                    }
                }                
                return Content("原图片上传成功");
            }
            catch(Exception ex)
            {
                return Content("上传失败" + ex.Message);
            }
        }
        #endregion

        #region 裁剪图片上传本地保存
        /// <summary>
        /// 裁剪图片上传本地保存
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="pw"></param>
        /// <param name="ph"></param>
        /// <param name="t">图片名称</param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult SaveImg(int x, int y, int w, int h, int pw, int ph, string t, string id)
        {
            try
            {
                WriteLog.WriteErrLog("进去裁剪图片", "开始位置");
                //string du= Session["startDate"].ToString();
                string DishesTypesPic = ConfigurationManager.AppSettings["Order_DishesTypes_Photos"] + "\\" + id;
                string DishesTypesPics = ConfigurationManager.AppSettings["WeChat_DishesTypes_Photos"] + "\\" + id;
                string[] stringArray = new string[] { DishesTypesPic, DishesTypesPics };

                foreach (var item in stringArray)
                {
                    string path = Path.Combine(item, Path.GetFileName(t));
                    var DishesTypePicName = Path.GetExtension(t);
                    string daPic = Path.Combine(item, Path.GetFileName(id + DishesTypePicName));
                    ///string xiaoPic = System.IO.Path.Combine(Server.MapPath("~/Mers"), System.IO.Path.GetFileName(id+"xiao.jpg"));
                    //Bitmap source = new Bitmap("E:/" + t);
                    Bitmap source = new Bitmap(path);
                    Bitmap resizeBitmap = new Bitmap(pw, ph);
                    Graphics g = Graphics.FromImage(resizeBitmap);
                    // 插值算法的质量
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(source, new Rectangle(0, 0, pw, ph), new Rectangle(0, 0, source.Width, source.Height), GraphicsUnit.Pixel);
                    g.Dispose();
                    Bitmap newImg = new Bitmap(w, h, PixelFormat.Format24bppRgb);
                    g = Graphics.FromImage(newImg);
                    g.DrawImage(resizeBitmap, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel);
                    g.Dispose();
                    Bitmap bm2 = new Bitmap(newImg, 120, 120);
                    bm2.Save(daPic);
                    //Bitmap bm1 = new Bitmap(newImg, 94, 94);
                    //bm1.Save(xiaoPic);
                    source.Dispose();
                }
                return Content("1");
            }
            catch (Exception ex)
            {
                WriteLog.WriteErrLog("进去裁剪图片", "异常位置");
                return Content("裁剪图片失败" + ex.Message);
            }
        }
        #endregion

        #region 图片转byte
        /// <summary>
        /// 图片转byte
        /// </summary>
        /// <param name="imagepath"></param>
        /// <returns></returns>
        public byte[] GetPictureData(string imagepath)
        {
            /**/
            ////根据图片文件的路径使用文件流打开，并保存为byte[] 
            FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法 
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }
        #endregion

        #region 保存上传图片路径
        /// <summary>
        /// 保存上传图片路径
        /// </summary>
        /// <param name="DishesTypeID"></param>
        /// <param name="PicName"></param>
        /// <returns></returns>
        public ActionResult ToLoadPic(string DishesTypeID, string PicName)
        {
            try
            {
                string DishesTypesPic = ConfigurationManager.AppSettings["Order_DishesTypes_Photos"] + "\\" + DishesTypeID;
                var DishesTypePicName = Path.GetExtension(PicName);
                string DishesTypePicURL = Path.Combine(DishesTypesPic, Path.GetFileName(DishesTypeID + DishesTypePicName));
                //byte[] dPic = GetPictureData(DishesTypePic); //获取商品图片字节流
                string DishesTypeURL = "/DishesTypes/" + DishesTypeID + DishesTypePicURL.Replace(DishesTypesPic, "").Replace('\\', '/'); //图片保存路径
                string results = service.UpdateDishesTypePhoto(DishesTypeID, DishesTypeURL, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(results);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")
                {
                    return Content(bs);
                }
                else { return Content("上传失败"); }
            }
            catch (Exception ex)
            {
                string e = ex.ToString();
                string daPiclog4 = Server.MapPath("~/异常");
                if (!Directory.Exists(daPiclog4))//判断目录是否存在
                {
                    Directory.CreateDirectory(daPiclog4);
                }
                return Content("上传失败" + ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 获取一级分类名称
        /// </summary>
        /// <param name="DishesTypeName"></param>
        /// <returns></returns>
        public ActionResult getDishesTypeByName(string DishesTypeName)
        {
            try
            {
                bool result = service.Get_Order_DishesTypeByName(DishesTypeName);
                if (result == true)
                {
                    return Json(true);
                }
                else
                {
                    return Json(false);
                }
            }
            catch (Exception) { return Json(false); }
        }

        /// <summary>
        /// 获取二级分类名称
        /// </summary>
        /// <param name="DishesTypeName"></param>
        /// <returns></returns>
        public ActionResult getDishesTypeByName2(string DishesTypeName)
        {
            try
            {
                bool result = service.Get_Order_DishesTypeByName2(DishesTypeName);
                if (result == true)
                {
                    return Json(true);
                }
                else
                {
                    return Json(false);
                }
            }
            catch (Exception) { return Json(false); }
        }

        /// <summary>
        /// 更新一二级商品顺序
        /// </summary>
        /// <param name="dishestypeidup">上级商品ID</param>
        /// <param name="dishestypeiddown">下级商品ID</param>
        /// <param name="postionup">上级标志</param>
        /// <param name="postiondown">下级标志</param>
        /// <returns></returns>
        public ActionResult UpdateDishesTypePostion(string dishestypeidup, string dishestypeiddown, int postionup, int postiondown)
        {
            try
            {
                string result = service.UpdateDishesTypePostion(dishestypeidup, dishestypeiddown, postionup, postiondown);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")
                {
                    return Content(bs);
                }
                else { return Content("更新失败"); }
            }
            catch (Exception ex)
            {
                return Content("更新失败" + ex.Message);
            }
        }

        /// <summary>
        /// 商品一二级排序
        /// </summary>
        /// <param name="DishesTypeID"></param>
        /// <param name="Postion"></param>
        /// <returns></returns>
        public ActionResult UpdateDishesTypeSort(string DishesTypeID,int Postion)
        {
            try
            {
                string result = "";
                View_OperUser user = (View_OperUser)Session[SessionStorage.OperUser];
                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }
                result = service.UpdateDishesTypeSort(user.OperID, DishesTypeID, Postion, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    return Content(bs);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Content("操作异常：" + ex.Message + "请联系管理员解决");
            }
        }

    }
}
